#!/usr/bin/env python
# -*- coding:utf-8 -*-

import threading
import socket
import struct
import sys
encoding = 'utf-8'
BUFSIZE = 1024
PORT = int(sys.argv[1])

class Reader(threading.Thread):
    def __init__(self, client):
        threading.Thread.__init__(self)
        self.client = client
        
    def run(self):
        while True:
            data_first = self.client.recv(4)
            if len(data_first) == 0 : continue
            data_size = struct.unpack('i',data_first)[0]
            #print(data_size)
            recevied_size = 0 #长度计数,解决粘包问题
            recevied_data = b''
            while recevied_size < data_size:
                data = self.client.recv(BUFSIZE)
                if(data):
                    recevied_size += len(data)
                    recevied_data += data
                    string = bytes.decode(recevied_data, encoding)
                    print(string,end="")
                else:
                    break        
    def readline(self):
        rec = self.inputs.readline()
        if rec:
            string = bytes.decode(rec, encoding)
            if len(string)>2:
                string = string[0:-2]
            else:
                string = ' '
        else:
            string = False
        return string
 
class Listener(threading.Thread):
    def __init__(self, port):
        threading.Thread.__init__(self)
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("0.0.0.0", port))
        self.sock.listen(0)
    def run(self):
        print("listener started ! Port Number is " + str(PORT) + " !" )
        while True:
            client, cltadd = self.sock.accept()
            Reader(client).start()
            cltadd = cltadd
 
lst  = Listener(PORT)
lst.start()
